// src/pages/employee-manager/ArchiveManagement.jsx
import { 
  Table, Button, Space, Input, message, Card, Upload, Row, Col, Typography, 
  Modal, Form, Divider, Tag, Popconfirm, Image, Tooltip, Progress
} from '@/utils/antd-imports';
import { 
  SearchOutlined, UploadOutlined, EyeOutlined, DeleteOutlined, 
  FileTextOutlined, DownloadOutlined, CheckCircleOutlined, CloseCircleOutlined 
} from '@/utils/icons';
import React, { useState, useEffect, useRef } from 'react';
import employeeApi from '../../api/employeeApi';
import fileApi from '../../api/fileApi';

const { Search } = Input;
const { TextArea } = Input;
const { Text, Title } = Typography;

// 档案类型配置
const ARCHIVE_TYPES = [
  { key: 'entryForm', label: '入职登记表', column: 'entry_form' },
  { key: 'idCardCopy', label: '身份证复印件', column: 'id_card_copy' },
  { key: 'diploma', label: '学历毕业证书', column: 'diploma' },
  { key: 'degreeCertificate', label: '学位证书', column: 'degree_certificate' },
  { key: 'bankCardCopy', label: '银行卡复印件', column: 'bank_card_copy' },
  { key: 'resume', label: '简历', column: 'resume' },
  { key: 'leavingCertificate', label: '离职证明', column: 'leaving_certificate' },
  { key: 'medicalReport', label: '三甲体检报告', column: 'medical_report' },
  { key: 'confidentialityAgreement', label: '保密协议', column: 'confidentiality_agreement' },
  { key: 'trainingAgreement', label: '员工培训协议', column: 'training_agreement' },
  { key: 'rulesConfirmation', label: '规章制度确认书', column: 'rules_confirmation' },
  { key: 'codeOfConduct', label: '员工行为准则', column: 'code_of_conduct' }
];

const ArchiveManagement = () => {
  const [employees, setEmployees] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [selectedEmployee, setSelectedEmployee] = useState(null);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewUrl, setPreviewUrl] = useState('');
  const [uploadingFiles, setUploadingFiles] = useState({});

  // 获取员工列表
  const fetchEmployees = async () => {
    setLoading(true);
    try {
      const params = {
        page: 1,
        pageSize: 1000, // 获取所有员工
        keyword: searchKeyword
      };
      const response = await employeeApi.getEmployeeList(params);
      
      if (response.code === 200 && response.data) {
        const employeeList = response.data.records || [];
        setEmployees(employeeList);
      } else {
        message.error('获取员工列表失败');
      }
    } catch (error) {
      console.error('获取员工列表失败:', error);
      message.error('获取员工列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchEmployees();
  }, []);

  // 检查档案是否已上传
  const hasArchive = (employee, archiveKey) => {
    return employee && employee[archiveKey] && employee[archiveKey].trim() !== '';
  };

  // 获取档案URL
  const getArchiveUrl = (employee, archiveKey) => {
    return hasArchive(employee, archiveKey) ? employee[archiveKey] : null;
  };

  // 显示预览
  const showPreview = async (url) => {
    setPreviewUrl(url);
    setPreviewVisible(true);
  };

  // 下载档案
  const downloadArchive = async (url, filename) => {
    try {
      const response = await fetch(url);
      const blob = await response.blob();
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(link.href);
      message.success('下载成功');
    } catch (error) {
      console.error('下载失败:', error);
      message.error('下载失败');
    }
  };

  // 上传档案
  const handleUpload = async (employee, archiveType, file) => {
    try {
      const uploadKey = `${employee.id}_${archiveType.key}`;
      setUploadingFiles(prev => ({ ...prev, [uploadKey]: true }));

      // 上传文件
      const uploadResult = await fileApi.uploadFile('employee', file, `${employee.name}/${archiveType.label}`);

      if (uploadResult.success && uploadResult.data && uploadResult.data.filePath) {
        const filePath = uploadResult.data.filePath;

        // 更新员工信息
        const updateData = {
          ...employee,
          [archiveType.key]: filePath
        };

        // 调用API更新员工档案
        await employeeApi.updateEmployee(updateData);
        
        // 更新本地状态
        setEmployees(prev => 
          prev.map(emp => 
            emp.id === employee.id 
              ? { ...emp, [archiveType.key]: filePath }
              : emp
          )
        );

        message.success(`${archiveType.label}上传成功`);
      } else {
        message.error(`${archiveType.label}上传失败`);
      }
    } catch (error) {
      console.error('上传失败:', error);
      message.error(`${archiveType.label}上传失败`);
    } finally {
      const uploadKey = `${employee.id}_${archiveType.key}`;
      setUploadingFiles(prev => ({ ...prev, [uploadKey]: false }));
    }
  };

  // 删除档案
  const handleDelete = async (employee, archiveType) => {
    try {
      // 更新员工信息，将对应字段设置为空
      const updateData = {
        ...employee,
        [archiveType.key]: ''
      };

      await employeeApi.updateEmployee(updateData);
      
      // 更新本地状态
      setEmployees(prev => 
        prev.map(emp => 
          emp.id === employee.id 
            ? { ...emp, [archiveType.key]: '' }
            : emp
        )
      );

      message.success(`${archiveType.label}已删除`);
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  };

  // 计算档案完整度
  const getArchiveCompleteness = (employee) => {
    const total = ARCHIVE_TYPES.length;
    const uploaded = ARCHIVE_TYPES.filter(type => hasArchive(employee, type.key)).length;
    return {
      uploaded,
      total,
      percentage: Math.round((uploaded / total) * 100)
    };
  };

  // 表格列定义
  const columns = [
    {
      title: '员工编号',
      dataIndex: 'employeeCode',
      key: 'employeeCode',
      width: 120,
      fixed: 'left',
      render: (text) => <Text code>{text || '-'}</Text>
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 100,
      fixed: 'left'
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department',
      width: 120
    },
    {
      title: '岗位',
      dataIndex: 'position',
      key: 'position',
      width: 120
    },
    {
      title: '档案完整度',
      key: 'completeness',
      width: 150,
      render: (_, record) => {
        const completeness = getArchiveCompleteness(record);
        return (
          <Tooltip title={`${completeness.uploaded}/${completeness.total} 已上传`}>
            <Progress 
              percent={completeness.percentage} 
              size="small" 
              status={completeness.percentage === 100 ? 'success' : 'active'}
            />
          </Tooltip>
        );
      }
    },
    ...ARCHIVE_TYPES.map(type => ({
      title: type.label,
      key: type.key,
      width: 100,
      align: 'center',
      render: (_, record) => {
        const hasFile = hasArchive(record, type.key);
        const fileUrl = getArchiveUrl(record, type.key);
        const uploadKey = `${record.id}_${type.key}`;
        const isUploading = uploadingFiles[uploadKey];

        return (
          <Space size="small">
            {hasFile ? (
              <>
                <Tooltip title="预览">
                  <Button
                    type="link"
                    icon={<EyeOutlined />}
                    size="small"
                    onClick={() => showPreview(fileUrl)}
                  />
                </Tooltip>
                <Tooltip title="下载">
                  <Button
                    type="link"
                    icon={<DownloadOutlined />}
                    size="small"
                    onClick={() => downloadArchive(fileUrl, `${record.name}_${type.label}`)}
                  />
                </Tooltip>
                <Popconfirm
                  title="确定要删除此档案吗？"
                  onConfirm={() => handleDelete(record, type)}
                  okText="确定"
                  cancelText="取消"
                >
                  <Tooltip title="删除">
                    <Button
                      type="link"
                      icon={<DeleteOutlined />}
                      size="small"
                      danger
                    />
                  </Tooltip>
                </Popconfirm>
              </>
            ) : (
              <Upload
                showUploadList={false}
                beforeUpload={(file) => {
                  const uploadKey = `${record.id}_${type.key}`;
                  if (uploadingFiles[uploadKey]) {
                    message.warning('正在上传中，请稍候...');
                    return false;
                  }
                  handleUpload(record, type, file);
                  return false;
                }}
                disabled={isUploading}
              >
                <Tooltip title="上传">
                  <Button
                    type="link"
                    icon={<UploadOutlined />}
                    size="small"
                    loading={isUploading}
                  />
                </Tooltip>
              </Upload>
            )}
          </Space>
        );
      }
    })),
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            size="small"
            onClick={() => setSelectedEmployee(record)}
          >
            详情
          </Button>
        </Space>
      )
    }
  ];

  // 筛选数据
  const filteredEmployees = employees.filter(emp => {
    if (!searchKeyword) return true;
    const keyword = searchKeyword.toLowerCase();
    return (
      emp.name?.toLowerCase().includes(keyword) ||
      emp.employeeCode?.toLowerCase().includes(keyword) ||
      emp.department?.toLowerCase().includes(keyword) ||
      emp.position?.toLowerCase().includes(keyword)
    );
  });

  // 员工详情模态框
  const renderEmployeeDetail = () => {
    if (!selectedEmployee) return null;

    const completeness = getArchiveCompleteness(selectedEmployee);

    return (
      <Modal
        title={`${selectedEmployee.name} - 档案详情`}
        open={!!selectedEmployee}
        onCancel={() => setSelectedEmployee(null)}
        footer={null}
        width={800}
      >
        <Divider>基本信息</Divider>
        <Row gutter={16}>
          <Col span={12}>
            <Text strong>员工编号：</Text>
            <Text>{selectedEmployee.employeeCode || '-'}</Text>
          </Col>
          <Col span={12}>
            <Text strong>姓名：</Text>
            <Text>{selectedEmployee.name}</Text>
          </Col>
          <Col span={12}>
            <Text strong>部门：</Text>
            <Text>{selectedEmployee.department || '-'}</Text>
          </Col>
          <Col span={12}>
            <Text strong>岗位：</Text>
            <Text>{selectedEmployee.position || '-'}</Text>
          </Col>
        </Row>

        <Divider>档案完整度</Divider>
        <Progress 
          percent={completeness.percentage} 
          status={completeness.percentage === 100 ? 'success' : 'active'}
        />
        <Text type="secondary">已上传 {completeness.uploaded}/{completeness.total} 项</Text>

        <Divider>档案列表</Divider>
        {ARCHIVE_TYPES.map(type => {
          const hasFile = hasArchive(selectedEmployee, type.key);
          const fileUrl = getArchiveUrl(selectedEmployee, type.key);
          const uploadKey = `${selectedEmployee.id}_${type.key}`;
          const isUploading = uploadingFiles[uploadKey];

          return (
            <Row key={type.key} gutter={16} style={{ marginBottom: 16 }}>
              <Col span={6}>
                <Text strong>{type.label}：</Text>
              </Col>
              <Col span={18}>
                {hasFile ? (
                  <Space>
                    <Tag color="green">
                      <CheckCircleOutlined /> 已上传
                    </Tag>
                    <Button
                      size="small"
                      icon={<EyeOutlined />}
                      onClick={() => showPreview(fileUrl)}
                    >
                      预览
                    </Button>
                    <Button
                      size="small"
                      icon={<DownloadOutlined />}
                      onClick={() => downloadArchive(fileUrl, `${selectedEmployee.name}_${type.label}`)}
                    >
                      下载
                    </Button>
                    <Popconfirm
                      title="确定要删除此档案吗？"
                      onConfirm={() => handleDelete(selectedEmployee, type)}
                    >
                      <Button
                        size="small"
                        danger
                        icon={<DeleteOutlined />}
                      >
                        删除
                      </Button>
                    </Popconfirm>
                  </Space>
                ) : (
                  <Space>
                    <Tag color="default">
                      <CloseCircleOutlined /> 未上传
                    </Tag>
                    <Upload
                      showUploadList={false}
                      beforeUpload={(file) => {
                        if (isUploading) {
                          message.warning('正在上传中，请稍候...');
                          return false;
                        }
                        handleUpload(selectedEmployee, type, file);
                        return false;
                      }}
                      disabled={isUploading}
                    >
                      <Button
                        size="small"
                        type="primary"
                        icon={<UploadOutlined />}
                        loading={isUploading}
                      >
                        上传
                      </Button>
                    </Upload>
                  </Space>
                )}
              </Col>
            </Row>
          );
        })}
      </Modal>
    );
  };

  return (
    <div style={{ padding: 24, background: '#f0f2f5', minHeight: '100vh' }}>
      <Card bordered={false}>
        <Row justify="space-between" align="middle" style={{ marginBottom: 24 }}>
          <Col>
            <Title level={3} style={{ margin: 0 }}>
              <FileTextOutlined style={{ marginRight: 8 }} />
              员工档案管理
            </Title>
          </Col>
          <Col>
            <Search
              placeholder="搜索员工编号/姓名/部门/岗位"
              allowClear
              enterButton
              style={{ width: 350 }}
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
            />
          </Col>
        </Row>

        <Table
          columns={columns}
          dataSource={filteredEmployees}
          loading={loading}
          bordered
          scroll={{ x: 2000 }}
          rowKey="id"
          pagination={{
            pageSize: 20,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条记录`
          }}
        />
      </Card>

      {/* 预览模态框 */}
      <Modal
        title="档案预览"
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        footer={null}
        width={800}
      >
        {previewUrl && (
          <div style={{ textAlign: 'center' }}>
            <Image
              src={previewUrl}
              alt="档案预览"
              style={{ maxWidth: '100%' }}
            />
          </div>
        )}
      </Modal>

      {/* 员工详情模态框 */}
      {renderEmployeeDetail()}
    </div>
  );
};

export default ArchiveManagement;

